package top.zhangjianyong.netty.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

public class TestHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        if (httpObject instanceof FullHttpRequest) {
            System.out.println("class: " + httpObject.getClass());
            System.out.println("ip:" + channelHandlerContext.channel().remoteAddress());
            ByteBuf msg = Unpooled.copiedBuffer("hello,client", CharsetUtil.UTF_8);
            FullHttpRequest request = (FullHttpRequest) httpObject;
            ByteBuf content = request.content();
            String s = content.toString(CharsetUtil.UTF_8);
            System.out.println(s);

            HttpResponse response =
                    new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, msg);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, msg.readableBytes());


            channelHandlerContext.channel().writeAndFlush(response);
        }else {
            ByteBuf msg = Unpooled.copiedBuffer("error!!!", CharsetUtil.UTF_8);
            HttpResponse response =
                    new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, msg);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, msg.readableBytes());
            channelHandlerContext.channel().writeAndFlush(response);
        }
    }
}
